package com.wdb007.venus.wss.service.impl;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wdb007.venus.svc.facade.BookgridService;
import com.wdb007.venus.svc.facade.ProcessInstructionService;
import com.wdb007.venus.svc.facade.process.model.ProcessInstructionLogDTO;
import com.wdb007.venus.wss.constants.WsAPPEnum;
import com.wdb007.venus.wss.service.WebSocketServerService;

import io.netty.channel.ChannelHandlerContext;

@Service("bookGridStatusResService")
public class BookGridStatusResService implements WebSocketServerService {
	
	private static Logger logger = LoggerFactory.getLogger(BookGridStatusResService.class);
	@Autowired
	private BookgridService bookgridService;
	@Autowired
	private ProcessInstructionService processInstructionService;
	@Resource(name="appService")
	private WebSocketServerService appService;
	
	@Override
	public String doService(ChannelHandlerContext ctx, String request) throws Exception {
		JSONObject jsonObj = JSON.parseObject(request);
		String bookGridId = "";
		try {
			String pushId = jsonObj.getString("pushId");
			bookGridId = jsonObj.getString("bookGridId");
			String status = jsonObj.getString("status");
			
			ProcessInstructionLogDTO pi = new ProcessInstructionLogDTO();
			pi.setContent(jsonObj.toJSONString());
			pi.setBookgridCode(bookGridId);
			pi.setDoorStatus(Integer.valueOf(status));
			pi.setInstructionGroupId(Long.valueOf(pushId));
			processInstructionService.statusRes(pi);
			
			logger.info("debug {}: 书格{}, 响应内容{}", jsonObj.getString("action"), bookGridId,jsonObj.toJSONString());
			String str = bookgridService.bookGridStatusReport(bookGridId, status);
			if(str == null) {
				return null ;
			}
			String[] arr = str.split("_");
			if("0".equals(arr[0])) {	//0表示运维人员进行开柜请求
				logger.info("运维人员[{}]进行开柜操作", arr[1]);
			}else if("1".equals(arr[0])) { //1表示开柜成功
				String userId = arr[1];
				JSONObject jsonApp = new JSONObject();
				jsonApp.put("action", WsAPPEnum.unlock_success.name());
				jsonApp.put("userid", userId);
				jsonApp.put("bookgrid_code", bookGridId);
				appService.doService(ctx, jsonApp.toJSONString());
			}else if("2".equals(arr[0])) { //2表示运维人员进行关柜
				logger.info("运维人员[{}]进行关柜操作", arr[1]);
			}else if("3".equals(arr[0])) { //3表示APP用户进行关柜
				String userId = arr[1];
				JSONObject jsonApp = new JSONObject();
				jsonApp.put("action", WsAPPEnum.lock_success.name());
				jsonApp.put("userid", userId);
				jsonApp.put("bookgrid_code", bookGridId);
				appService.doService(ctx, jsonApp.toJSONString());
			}else {
				logger.info("未能失败的书格状态[{}]", status);
			}
		} catch (Exception e) {
			logger.error("单书格状态上报"+bookGridId+"异常error", e);
		}
		return null;
	}

}
